package cn.fangline.camerademo02;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.math.BigDecimal;


public class MainActivity extends Activity {

	/**
	 * Called when the activity is first created.
	 */
	//设置LOG标签
	private static final String TAG = "sensor";
	private SensorManager sm;
	private TextView x, y, z, a, b;
	private Button turn, photo;

	private int s1= Sensor.TYPE_ACCELEROMETER;

	private int s2 = Sensor.TYPE_ROTATION_VECTOR;


	private OrientationEventListener mOrientationListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		x = findViewById(R.id.x);
		y = findViewById(R.id.y);
		z = findViewById(R.id.z);
		a = findViewById(R.id.a);
		b = findViewById(R.id.b);
		turn = findViewById(R.id.turn);
		turn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, LineActivity.class));
			}
		});

		photo = findViewById(R.id.photo);

		photo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, CamerakitActivity	.class));
			}
		});

		//创建一个SensorManager来获取系统的传感器服务
		sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


		/*
		 * 最常用的一个方法 注册事件
		 * 参数1 ：SensorEventListener监听器
		 * 参数2 ：Sensor 一个服务可能有多个Sensor实现，此处调用getDefaultSensor获取默认的Sensor
		 * 参数3 ：模式 可选数据变化的刷新频率
		 * */
		sm.registerListener(myAccelerometerListener, sm.getDefaultSensor(s1), SensorManager.SENSOR_DELAY_NORMAL);
		sm.registerListener(myAccelerometerListener, sm.getDefaultSensor(s2), SensorManager.SENSOR_DELAY_NORMAL);


		mOrientationListener = new OrientationEventListener(this) {
			@Override
			public void onOrientationChanged(int rotation) {
				if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315) || ((rotation >= 135) && (rotation <= 225))) {
					//portrait
					Log.d(TAG, "Screen orientation is Portrait!");
				} else if (((rotation > 45) && (rotation < 135)) || ((rotation > 225) && (rotation < 315))) {
					//landscape
					Log.d(TAG, "Screen orientation is Landscape!");
				}
				a.setText(rotation + "");
			}
		};
		mOrientationListener.enable();

	}

	/*
	 * SensorEventListener接口的实现，需要实现两个方法
	 * 方法1 onSensorChanged 当数据变化的时候被触发调用
	 * 方法2 onAccuracyChanged 当获得数据的精度发生变化的时候被调用，比如突然无法获得数据时
	 * */
	final SensorEventListener myAccelerometerListener = new SensorEventListener() {

		//复写onSensorChanged方法
		public void onSensorChanged(SensorEvent sensorEvent) {
			if (sensorEvent.sensor.getType() == s1) {
				Log.i(TAG, "onSensorChanged");

				//图解中已经解释三个值的含义
				float X_lateral = sensorEvent.values[0];
				float Y_longitudinal = sensorEvent.values[1];
				float Z_vertical = sensorEvent.values[2];
				Log.i(TAG, "\n heading " + X_lateral);
				Log.i(TAG, "\n pitch " + Y_longitudinal);
				Log.i(TAG, "\n roll " + Z_vertical);
				x.setText(X_lateral + "");
				y.setText(Y_longitudinal + "");
				z.setText(Z_vertical + "");
			}

			if(sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
				calculateRotateAngle(sensorEvent);
			}
		}

		//复写onAccuracyChanged方法
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			Log.i(TAG, "onAccuracyChanged");
		}
	};


	/*
	 *计算旋转角度
	 * @param event
	 */
	private void calculateRotateAngle(SensorEvent event) {
		float[] rotationMatrix = new float[16];
		SensorManager.getRotationMatrixFromVector(
				rotationMatrix, event.values);
		// Remap coordinate system
		float[] remappedRotationMatrix = new float[16];
		SensorManager.remapCoordinateSystem(rotationMatrix,
				SensorManager.AXIS_X,
				SensorManager.AXIS_Z,
				remappedRotationMatrix);

		// Convert to orientations
		float[] orientations = new float[3];
		SensorManager.getOrientation(remappedRotationMatrix, orientations);
		for (int i = 0; i < 3; i++) {
			orientations[i] = (float) (Math.toDegrees(orientations[i]));
		}
//        Timber.i("旋转角度：%f", orientations[2]);
		// 保留2位小数
		float deviceRotationAngle = new BigDecimal(orientations[2]).setScale(2, 4).floatValue();
		b.setText("角度：x:" + orientations[0] + "y:"+orientations[1] + "z:" + orientations[2]);
//		b.setText("角度：" + deviceRotationAngle);
	}

	@Override
	protected void onResume() {
		super.onResume();
		//选取加速度感应器
		sm.registerListener(myAccelerometerListener, sm.getDefaultSensor(s1), SensorManager.SENSOR_DELAY_NORMAL);
		sm.registerListener(myAccelerometerListener, sm.getDefaultSensor(s2), SensorManager.SENSOR_DELAY_NORMAL);
	}

	public void onPause() {
		/*
		 * 很关键的部分：注意，说明文档中提到，即使activity不可见的时候，感应器依然会继续的工作，测试的时候可以发现，没有正常的刷新频率
		 * 也会非常高，所以一定要在onPause方法中关闭触发器，否则讲耗费用户大量电量，很不负责。
		 * */
		sm.unregisterListener(myAccelerometerListener);
		super.onPause();
	}


}
